package com.sl.plugin.step.delay;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;

import java.util.List;
import java.util.Map;

/**
 */
//@Compensation(listener = NormalRowListener.class, type = CompensationType.SERVICE_COMPENSATION)
public class DelayComp extends AbstractProcessComp<List<Map<String, Object>>, List<Map<String, Object>>> implements ProcessCompService {

    public DelayComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);

        Boolean firstDelayFlag = meta.getBoolAttr("output.firstDelayFlag");

        if (BooleanUtil.isTrue(firstDelayFlag)) {
            data.setSize(Integer.MAX_VALUE);
        } else {
            data.setSize(1);
        }

    }


    @Override
    public List<Map<String, Object>> input(List<Map<String, Object>> param) {

        delay();

        return param;
    }


    private void delay() {
        int multiple = 1000;
        Long delayTime = meta.getLongAttr("output.delayTime");
        if(ObjectUtil.isNull(delayTime)){
            return;
        }
        try {
            // starttime (in seconds ,Minutes or Hours)
            double timeStart = (double) System.currentTimeMillis() / (double) multiple;
            double iMaximumTimeout = delayTime / multiple;
            boolean continueLoop = true;
            while (continueLoop && !isStopped()) {
                // Update Time value
                double now = (double) System.currentTimeMillis() / (double) multiple;
                // Let's check the limit time
                if ((iMaximumTimeout >= 0) && (now >= (timeStart + iMaximumTimeout))) {
                    continueLoop = false;
                } else {
                    Thread.sleep(100);
                }
            }
        } catch (Exception e) {
            // We get an exception
            logError("Error  : " + e.getMessage());
            if (Thread.currentThread().isInterrupted()) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
